package com.k2091.washcar.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.k2091.washcar.common.Userinfo;
import com.k2091.washcar.entity.Users;
import com.k2091.washcar.entity.WxUserinfo;
import com.k2091.washcar.service.IUsersService;
import com.k2091.washcar.service.IWxUserinfoService;
import com.k2091.washcar.util.HttpUtils;
import net.sf.json.JSONObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;

@RestController
public class LoginController {
    @Resource
    private IWxUserinfoService userinfoService;

    @GetMapping("/login")
    public HashMap<String, Object> login(String code) {
        QueryWrapper queryWrapper = new QueryWrapper();
        //存储返回的数据
        HashMap<String, Object> map = new HashMap<>();
        //给微信官方发送请求获取 用户的openid 和 session_key
        String res = HttpUtils.doGet("https://api.weixin.qq.com/sns/jscode2session?" +
                "appid=" + Userinfo.APPID + "&" +
                "secret=" + Userinfo.SECRET + "&" +
                "js_code=" + code + "&" +
                "grant_type=authorization_code", null);
        //将返回的json字符串转换为json对象
        JSONObject jsonObj = JSONObject.fromObject(res);
        map.put("session_key", jsonObj.get("session_key").toString());
        map.put("openid", jsonObj.get("openid").toString());
        //根据openid 去数据库查询是否存在该用户 存在返回true 不存在返回false
        queryWrapper.eq("openid", map.get("openid"));
        WxUserinfo user = userinfoService.getOne(queryWrapper);
        if (user == null) {
            map.put("isexist", false);
        } else {
            map.put("isexist", true);
            map.put("userinfo", user);
        }
        return map;

    }

    @GetMapping("/registe")
    public Boolean registe(String openid, String userinfo) {
        //如果为新用户 小程序将openid和用户信息发送给后台 进行注册
        JSONObject jsonObj = JSONObject.fromObject(userinfo);
        WxUserinfo ccUserinfo = new WxUserinfo();
        ccUserinfo.setNickname(jsonObj.get("nickName").toString());
        ccUserinfo.setAvatarurl(jsonObj.get("avatarUrl").toString());
        ccUserinfo.setCountry(jsonObj.get("country").toString());
        ccUserinfo.setProvince(jsonObj.get("province").toString());
        ccUserinfo.setCity(jsonObj.get("city").toString());
        ccUserinfo.setGender(Integer.parseInt(jsonObj.get("gender").toString()));
        ccUserinfo.setLanguage(jsonObj.get("language").toString());
        ccUserinfo.setOpenid(openid);
        return userinfoService.save(ccUserinfo);
    }
}
